import Promise from 'promise';
import { UserModel } from '../models';
import { debug } from '../../config';
import * as ResultMsg from '../constrants/ResultMsg';
import { errorRender } from '../common/response';
import { MessageProxy, UserProxy } from '../proxy';
import config from '../config';
import validator from 'validator';

/**
 * 需要管理员权限
 */
export function adminRequired(req, res, next) {
  if (!req.session || !req.session.user) {
    req.session._loginReferer = req.headers.referer;
    return res.render('sign/signin');
  }

  if (!req.session.user.isAdmin) {
    return next('需要管理员权限');
  }

  next();
}

export function supportRequired(req, res, next) {
  if (!req.session || !req.session.user) {
    req.session._loginReferer = req.headers.referer;
    return res.render('sign/signin');
  }

  if (!req.session.user.isSupport && !req.session.user.isAdmin) {
    return next('需要运营权限权限');
  }

  next();
}

/**
 * 需要登录
 */
export function userRequired(req, res, next) {
  if (!req.session || !req.session.user || !req.session.user._id) {
    return next('需要登录!');
  }

  next();
}

export function blockUser() {
  return function (req, res, next) {
    if (req.path === '/signout') {
      return next();
    }

    if (req.session.user && req.session.user.is_block && req.method !== 'GET') {
      return next('您已被管理员屏蔽了。有疑问请联系 @shuoriyu。');
    }

    next();
  };
}

export function gen_session(user, res) {
  const auth_token = `${user._id}$$$$`; // 以后可能会存储更多信息，用 $$$$ 来分隔
  const opts = {
    path: '/',
    maxAge: 1000 * 60 * 60 * 24 * 30,
    signed: true,
    httpOnly: true,
  };
  res.cookie(config.auth_cookie_name, auth_token, opts); // cookie 有效期30天
}

// 验证用户是否登录
export function authUser(req, res, next) {
  // Ensure current_user always has defined.
  const appId = res.locals.appId;
  res.locals.current_user = null;

  if (req.session.user) {
    const user = req.session.user;
    if (config.admins.hasOwnProperty(user.loginname) || user.role === 'A') {
      user.isAdmin = true;
    } else if (user.role === 'S') {
      user.isSupport = true;
    } else {
      user.isNormal = true;
    }

    res.locals.current_user = req.session.user = user;
    next();
  } else {
    const auth_token = req.signedCookies[config.auth_cookie_name];
    if (auth_token) {
      const auth = auth_token.split('$$$$');
      const userId = auth[0];
      if (userId) {
        UserProxy.findOneById(appId, userId)
          .then((user) => {
            if (user) {
              user = user.toObject();
              if (config.admins.hasOwnProperty(user.loginname) || user.role === 'A') {
                user.isAdmin = true;
              } else if (user.role === 'S') {
                user.isSupport = true;
              } else {
                user.isNormal = true;
              }

              res.locals.current_user = req.session.user = user;
            }

            next();
          })
          .catch(err => next(err));
      } else {
        next();
      }
    } else {
      next();
    }
  }
}
